<template>
  <main class="main-container">
    <div style="text-align: right">
      <el-button type="primary" size="large" @click="editVisible = true"
        >新增商品</el-button
      >
    </div>
    <el-table :data="tableData">
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="pic" label="图片">
        <template #default="{ row }">
          <img :src="fileUrl + row.pic" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column
        prop="commentCount"
        label="评论数"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="salesVolume"
        label="销售量"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          {{ row.salesVolume || 0 }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="
              editVisible = true;
              productForm = JSON.parse(JSON.stringify(row));
            "
            >编辑</el-button
          >
          <el-button type="danger" link @click="del(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      style="margin-top: 20px"
      v-model:current-page="queryParams.page"
      @current-change="getData"
    />
    <el-drawer
      @closed="productForm = new ProductForm()"
      :title="productForm.id ? '编辑商品' : '新增商品'"
      v-model="editVisible"
    >
      <el-form
        ref="productFormRef"
        v-if="editVisible"
        :model="productForm"
        label-width="80px"
        :rules="{
          title: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
          ],
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            {
              validator: (rule:any, value:any, callback:any) => {
                // 判断是否为数字
                if (isNaN(value)) {
                  callback(new Error('价格必须为数字值'));
                } else if (value <= 0) {
                  callback(new Error('价格必须大于0'));
                } else {
                  callback();
                }
              },
              trigger: 'blur',
            },
          ],
          pic: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
        }"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="productForm.title" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="productForm.price" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品图片" prop="pic">
          <el-upload
            :action="`${baseUrl}/upload`"
            :show-file-list="false"
            limit="1"
            :onSuccess="handleSuccess"
          >
            <img
              v-if="productForm.pic"
              :src="fileUrl + productForm.pic"
              width="146px"
              height="146px"
            />
            <div
              v-else
              style="
                width: 146px;
                height: 146px;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #f0f0f0;
                border: 1px dashed #ccc;
              "
            >
              <el-icon><Plus /></el-icon>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </main>
</template>
<script setup lang="ts">
import { ref } from "vue";
import productService from "@/api/product";
import type { Product, ProductResponse } from "@/api/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus/lib";
const fileUrl = window.config.fileUrl;
const baseUrl = window.config.baseUrl;
const tableData = ref<ProductResponse[]>([]);
const productFormRef = ref<FormInstance>();
const editVisible = ref(false);
const total = ref(0);
class ProductForm implements Product {
  id?: number;
  price: number = 0;
  title: string = "";
  pic: string = "";
}
const productForm = ref<ProductForm>(new ProductForm());
const del = (id: number) => {
  ElMessageBox.confirm("此操作将删除该商品, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await productService.deleteProduct(id);
      getData();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
const handleSuccess = (res: any) => {
  productForm.value.pic = res.filename;
};
const submit = async () => {
  productFormRef.value!.validate(async (valid) => {
    if (!valid) {
      return;
    }
    await productService.updateProduct(productForm.value);
    editVisible.value = false;
    getData();
    ElMessage.success("提交成功");
  });
};
const queryParams = ref({
  page: 1,
  limit: 10,
});
const getData = async () => {
  let res = await productService.fetchProducts(queryParams.value);
  total.value = res.data.totalCount;
  tableData.value = res.data.products;
};
getData();
</script>
<style scoped lang="less"></style>
